package com.codebase.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;

/**
 * 删除节点
 */
public class Delete {

    private CuratorFramework client;

    @Before
    public void before(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .build();
    }

    /**
     * 删除节点
     */
    public void test() throws Exception{
        String path = "/root";
        client.start();
        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, "111".getBytes());
        Stat stat = new Stat();
        client.getData().storingStatIn(stat).forPath(path);

        client.delete()
                .guaranteed()    //强制删除，只要客户端会话有效，那么后台就持续删除，直到删除为止
                .deletingChildrenIfNeeded()  //删除一个节点，并递归删除所有的子节点
                .withVersion(stat.getVersion())
                .forPath(path);
    }


}
